package com.gframework.util;

import java.security.SecureRandom;

/**
 * UUID辅助工具类
 * 
 * @since 1.0.0
 * @author Ghwolf
 *
 */
public class UUIDUtils {
	private UUIDUtils(){}
	
	private static final SecureRandom secure = new SecureRandom();
	
	/**
	 * 取得一个安全的随机的32位的UUID（无横线），并转换为字符串.
	 * <p>此方法使用的是java原生的
	 * @return 返回一个UUID字符串
	 */
	public static String secure32UUID() {
		byte[] randomBytes = new byte[16];
		secure.nextBytes(randomBytes);
        randomBytes[6]  &= 0x0f;  /* clear version        */
        randomBytes[6]  |= 0x40;  /* set to version 4     */
        randomBytes[8]  &= 0x3f;  /* clear variant        */
        randomBytes[8]  |= 0x80;  /* set to IETF variant  */
        long msb = 0;
        long lsb = 0;
        for (int i=0; i<8; i++)
            msb = (msb << 8) | (randomBytes[i] & 0xff);
        for (int i=8; i<16; i++)
            lsb = (lsb << 8) | (randomBytes[i] & 0xff);
        
        return digits(msb >> 32, 8) + 
                digits(msb >> 16, 4) + 
                digits(msb, 4) + 
                digits(lsb >> 48, 4) + 
                digits(lsb, 12);
	}
	
	/** Returns val represented by the specified number of hex digits. */
	private static String digits(long val, int digits) {
        long hi = 1L << (digits * 4);
        return Long.toHexString(hi | (val & (hi - 1))).substring(1);
    }
}
